package mo.leetcode_hot;

import mo.common.ListNode;

import java.util.Arrays;

public class L148 {

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;   //分治
        ListNode dummy = new ListNode(0);
        ListNode res = dummy;
        ListNode left = sortList(head);
        ListNode right = sortList(tmp);
        while (left != null && right != null) {
            if (left.val < right.val) {
                dummy.next = left;
                left = left.next;
            } else {
                dummy.next = right;
                right = right.next;
            }
            dummy = dummy.next;
        }
        dummy.next = left != null ? left : right;
        return res.next;
    }

    public static void main(String[] args) {
        L148 test = new L148();
        ListNode node = ListNode.convertList2ListNode(Arrays.asList(4, 2, 1, 3));
        System.out.println(test.sortList(node));
    }

}
